<template>
	<view class="page-make-photo-print">
		<view v-if="!addressObj" class="add-address flex-center" @tap="toAddress">
			<text class="add-icon">+</text>
			<text class="add-text">添加收货地址</text>
		</view>
		<view v-else @tap="toAddress" class="address-item flex-between-center">
			<view class="left-info">
				<text class="normal-title-bold">{{addressObj.area}}{{addressObj.address}}</text>
				<text class="desc">{{addressObj.consignee}}&nbsp;&nbsp;{{addressObj.phone}}</text>
			</view>
			<u-icon @tap.stop="toAddress" color="rgba(229, 229, 229, 1)" name="arrow-right"></u-icon>
		</view>
		<u-gap height="10" bgColor="rgba(245, 245, 245, 1)"></u-gap>

		<photo-info :detailInfo="detailInfo" imageUrlAttr="typesetUrl" />

		<u-gap height="10" bgColor="rgba(245, 245, 245, 1)"></u-gap>
		<view class="print-info">
			<view class="detail-item">
				<text>冲印版数（一版{{detailInfo.printNum}}小张）</text>
				<text>1</text>
				<!-- 	<view>
					<u-number-box button-size="24" v-model="printNum"></u-number-box>
				</view> -->

			</view>

			<view v-for="item in printServices" :key="item.id" class="detail-item">
				<text>{{item.name}}</text>
				<view>
					<text class="origin-price">&yen;{{item.amount}}</text>
					<text>&yen;{{item.discount}}</text>
				</view>

			</view>

		</view>
		<u-gap height="10"></u-gap>
		<view class="express-info">
			<view class="express-title">
				<text>快递服务</text>
			</view>
			<view class="detail-item" v-for="(item,index) in expressList" :key="item.id" @tap="onExpressChange(item)">
				<text>{{item.name}}</text>
				<view class="flex-center">
					<view class="mr-4">
						<text class="origin-price">&yen;{{item.amount}}</text>
						<text>&yen;{{item.discount}}</text>
					</view>
					<image class="radio-icon" v-if="expressId === item.id" src="/static/other/radio-checked.svg">
					</image>
					<image class="radio-icon" v-else src="/static/other/radio-uncheck.png"></image>
				</view>
			</view>
			<view class="desc">
				<text>*支付成功后，下载的电子照会自动去除水印</text>
			</view>
		</view>

		<view class="pay-box">

			<view class="text-box">
				<text>应付款：</text>
				<text class="amount">&yen;{{payAmount / 100}}</text>
			</view>
			<view class="pay-btn">
				<view class="custom-button full-button" @tap="onPay">
					<u-button type="primary" shape="circle" text="确认支付"></u-button>
				</view>
			</view>
		</view>

	</view>
	<custom-pay-popup v-model:show="showPayPopup" ref="customPayPopup" :payAmount="payAmount" @pay="onConfirmPay"
		@paySuccess="onPaySuccess" />

</template>

<script setup>
	import CustomPayPopup from '@/components/custom-pay-popup/custom-pay-popup.vue';
	import photoInfo from '@/components/photo-info/photo-info.vue';
	import {
		onLoad,
		onShow,
	} from '@dcloudio/uni-app';
	import {
		ref,
		shallowRef,
		reactive,
		computed,
	} from "vue";
	import {
		queryPackageApi,
		saveAllPhoto,
		getPaymentType,
	} from '@/common/js/method.js';
	import {
		payType,
		directPayPlatforms,
	} from '@/common/js/data.js';

	const loginProvider = uni.getStorageSync('loginProvider');
	const customPayPopup = ref(null);
	const printNum = ref('1');
	const printServices = shallowRef([]);
	const addressObj = shallowRef(null);
	const expressList = shallowRef([]);
	const busiType = ref('make-photo');
	const detailInfo = ref({});
	const showPayPopup = ref(false);
	const expressId = ref('');

	// 计算支付金额（所有服务的折扣价之和）
	const payAmount = computed(() => {
		if (!printServices.value.length || !expressList.value.length) return 0;
		const printPrice = printServices.value.reduce((t, c) => t + c.discount, 0);
		const express = expressList.value.find(item => item.id === expressId.value);
		return Number(printPrice * 100) + Number(express.discount * 100);
	});

	// 套餐类型，1-充值套餐，2-保存电子照套餐，3-冲印邮寄套餐，4-快递方式套餐 5-照片剪辑套餐，6-换底色套餐，7-黑白上色套餐，8-漫画照套餐，9-素描化套餐，10-画质增强套餐，11-证件照打印，12-生活照打印
	const packType = computed(() => {
		let res;
		if (busiType.value === 'make-photo') { //证件照制作-冲印邮寄套餐
			res = 3;
		} else if (busiType.value === 'photo-cut') { //证件照裁剪
			res = 5;
		} else if (busiType.value === 'change-background') { //换底色
			res = 6;
		}
		return res;
	})

	// 下单接口的recordType字段
	//照片类型，1-保存电子照，2-冲印邮寄，3-证件照裁剪，4-换底色套餐，5-人像素描照，6-人像漫画照，7-黑白上色照，8-老照片修复，9-修改DPI，10-图片格式转换,11-证件照打印，12-生活照打印
	const recordType = computed(() => {
		const recordTypeMap = {
			'make-photo': 2, //证件照制作-冲印邮寄
			'change-background': 4, //换底色-冲印邮寄
		};
		return recordTypeMap[busiType.value];
	})


	const toAddress = () => {
		const params = {};
		uni.navigateTo({
			url: `/pages/address/address?data=${JSON.stringify(params)}`,
		})
	}


	// 查询套餐
	const getPackageInfo = async () => {
		// 套餐类型，1-充值套餐，2-保存电子照套餐，3-冲印邮寄套餐，4-快递方式套餐 5-照片剪辑套餐，6-换底色套餐，7-黑白上色套餐，8-漫画照套餐，9-素描化套餐，10-画质增强套餐，11-证件照打印，12-生活照打印
		let res = await queryPackageApi([3, 4])
		printServices.value = res[0].data.packageList;
		expressList.value = res[1].data.packageList;
		expressId.value = res[1].data.packageList[0].id;
	}


	// 查询默认地址
	const getDefaultAddress = async () => {
		const res = await uni.$request('/api/user/address/select/default');
		if (res.data) {
			addressObj.value = res.data;
		}
	}

	// 确认支付
	const onConfirmPay = async ({
		type,
		callback,
	}) => {
		// 微信支付需要的信息
		const payInfo = await getPayInfo(type);
		callback(payInfo)
	}

	// 获取微信支付接口需要的信息
	const getPayInfo = async (type) => {
		console.log('detailInfo', detailInfo.value)
		console.log('addressObj', addressObj.value)
		console.log('printServices', printServices.value)

		const {
			id,
			widthPixel,
			heightPixel,
			photoKey,
			minSize,
			maxSize,
			printNum,
			backColor
		} = detailInfo.value;
		let res = await uni.$request('/api/busi/print/addOrder', {
			addressId: addressObj.value.id, //地址id
			packageId: printServices.value[0].id, //冲印服务的id
			recordType: recordType.value,
			productId: id, //主键id
			width: widthPixel,
			height: heightPixel,
			expressId: expressId.value,
			photoKey, //预览接口返回的photoKey
			payType: payType[type], //支付方式，0-金豆，1-微信，2-支付宝，3-抖音，4-银联
			bkColor: backColor,
			payAmount: payAmount.value,
			photoStyle: 1, //图像格式，1-jpg,2-png,3-jpeg，默认是jpg
			photoSize: [minSize, maxSize].join(','),
			printNum,
		});
		return res.data;
	}


	const onPay = async () => {
		if (!addressObj.value) {
			uni.$u.toast('请添加收货地址');
			return;
		}

		// 直接调支付的平台
		if (directPayPlatforms.includes(loginProvider)) {
			let paymentType = await getPaymentType();
			onConfirmPay({
				type: paymentType,
				callback: async (payInfo) => {
					let res = await uni.$pay(payInfo);
					onPaySuccess(res);
				},
			})
		} else {
			showPayPopup.value = true;
		}
	}

	const toSuccess = () => {
		setTimeout(() => {
			// 支付成功，跳转结果页
			uni.navigateTo({
				url: `/pages/make-photo/make-photo-print-res`,
			});
		}, 1000);
	}

	const onPaySuccess = async ({
		orderNo
	}) => {
		// 支付成功，证件照制作
		let res = await uni.$request('/api/busi/photo/take', {
			orderNo,
			orderType: 2,
		});
		await saveAllPhoto(res.data)
		toSuccess();
	};



	const onExpressChange = (item) => {
		expressId.value = item.id;
	};
	const getAddressIfExsit = (item) => {
		const data = uni.getStorageSync('choosedAddresInfo');
		console.log('获取到选择的地址', data);
		if (data) {
			addressObj.value = data;
		}
		uni.removeStorageSync('choosedAddresInfo');
		return data;
	}

	onShow((params) => {
		getAddressIfExsit();
	})
	onLoad((params) => {
		busiType.type = params.type;
		const data = JSON.parse(params.data)
		detailInfo.value = {
			...data,
			typesetUrl: decodeURIComponent(data.typesetUrl),
		};
		getPackageInfo();
		// 如果不存在传入地址，就查询
		if (!getAddressIfExsit()) {
			getDefaultAddress();
		}
	})
</script>

<style lang="less" scoped>
	.page-make-photo-print {
		box-sizing: border-box;
		padding: 20rpx 32rpx 252rpx 32rpx;
		height: 100vh;
		overflow-y: auto;
		background: rgba(245, 245, 245, 1);

		.detail-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			/** 文本 */
			font-size: 28rpx;
			line-height: 40rpx;
			color: rgba(56, 56, 56, 1);
		}

		.add-address {
			box-sizing: border-box;
			gap: 8rpx;
			height: 98rpx;
			border-radius: 16rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 2rpx 4rpx rgba(0, 0, 0, 0.02);
			padding: 28rpx;

			.add-icon {
				font-size: 56rpx;
				color: rgba(166, 166, 166, 1);
				margin-bottom: 6rpx;
			}

			.add-text {
				margin-top: 6rpx;
				font-size: 28rpx;
				line-height: 40rpx;
				color: rgba(56, 56, 56, 1);
			}
		}

		.address-item {
			border-radius: 16rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 2rpx 4rpx rgba(0, 0, 0, 0.02);
			padding: 32rpx;

			.left-info {
				display: flex;
				flex-direction: column;
				gap: 10px;
			}

			.edit-icon {
				width: 48rpx;
				height: 48rpx;
			}
		}

		.print-info {
			border-radius: 16rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 2rpx 4rpx rgba(0, 0, 0, 0.02);
			display: flex;
			flex-direction: column;
			gap: 20rpx;
			padding: 32rpx;


		}

		.express-info {
			border-radius: 16rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 2rpx 4rpx rgba(0, 0, 0, 0.02);
			padding: 32rpx;
			display: flex;
			flex-direction: column;
			gap: 30rpx;

			.express-title {
				font-size: 32rpx;
				font-weight: 700;
				line-height: 48rpx;
				color: rgba(56, 56, 56, 1);
			}
		}

		.pay-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			box-sizing: border-box;
			height: 212rpx;
			border-radius: 32rpx 32rpx 0 0;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px -4rpx 12rpx rgba(0, 0, 0, 0.02);
			padding: 32rpx 32rpx 68rpx 32rpx;
			position: fixed;
			left: 0;
			bottom: 0;

			.text-box {
				font-size: 36rpx;
				color: rgba(0, 0, 0, 1);

				.amount {
					font-weight: 700;
					color: rgba(69, 145, 230, 1);
				}


			}

			.pay-btn {
				width: 160px;
			}
		}
	}
</style>